package com.xw.class06;

import java.util.Arrays;
import java.util.Comparator;

/**
 * @author: xw
 * @create: 2022/10/17 10:21
 * @description: 比较器
 */
public class Code01_Comparator {

    public static class Student{
        public String name;
        public int age;
        public int id;

        public Student(String name, int age, int id) {
            this.name = name;
            this.age = age;
            this.id = id;
        }

        @Override
        public String toString() {
            return "Student{" +
                    "name='" + name + '\'' +
                    ", age=" + age +
                    ", id=" + id +
                    '}';
        }

        // 任何比较器：
        // compare方法里，遵循一个统一的规范：
        // 返回负数的时候，认为第一个参数应该排在前面
        // 返回正数的时候，认为第二个参数应该排在前面
        // 返回0的时候，认为无所谓谁放前面
        public static class IdDescending implements Comparator<Student> {
            @Override
            public int compare(Student o1, Student o2) {
                return o1.id - o2.id;
            }
        }

        public static class AgeAscIdDesc implements Comparator<Student>{

            @Override
            public int compare(Student o1, Student o2) {
                int ageFlag = o1.age - o2.age;
                if( ageFlag< 0){
                    return -1;
                }else if (ageFlag > 0){
                    return 1;
                }else{
                    return o2.id - o1.id ;
                }

            }
        }
    }

    public static void main(String[] args) {
        Student student1 = new Student("A", 4, 40);
        Student student2 = new Student("B", 4, 21);
        Student student3 = new Student("C", 3, 12);
        Student student4 = new Student("D", 3, 62);
        Student student5 = new Student("E", 3, 42);
        // D E C A B

        Student[] students = new Student[]{student1, student2, student3, student4, student5};
        System.out.println("第一条打印");

        Arrays.sort(students, new Student.AgeAscIdDesc());
        for (int i = 0; i < students.length; i++) {
            Student s = students[i];
            System.out.println(s.name + "," + s.id + "," + s.age);
        }
    }
}
